package com.itheima.utils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;

/**
 * <p>Description: 阿里云发送短信服务</p>
 *
 * @author liuyiming
 * @date 2022-10-12 19:50
 * @version 1.0.0
 */
public class SMSUtils {
    public static void sendMsg(String signName, String templateCode,String phoneNumbers,String param){
        //参数：地区、申请的KeyID、秘钥
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI5t6Lw2y7a4nvz95q5ftk", "1zl0muG6hXNLnOsXM6SwjvJLRJq8tY");
        /** use STS Token
         DefaultProfile profile = DefaultProfile.getProfile(
         "<your-region-id>",           // The region ID
         "<your-access-key-id>",       // The AccessKey ID of the RAM account
         "<your-access-key-secret>",   // The AccessKey Secret of the RAM account
         "<your-sts-token>");          // STS Token
         **/

        IAcsClient client = new DefaultAcsClient(profile);

        SendSmsRequest request = new SendSmsRequest();
        /*短信标头：因为是测试，所以不可修改*/
        //request.setSignName("阿里云短信测试");
        request.setSignName(signName);
        /*模板编码：因为是测试，所以不可修改*/
        //request.setTemplateCode("SMS_154950909");
        request.setTemplateCode(templateCode);
        /*要发送的手机号，因为是设置，所以只能设置绑定的那几个*/
        request.setPhoneNumbers(phoneNumbers);
        /*code是固定的，后边是要发送的验证码的内容*/
        request.setTemplateParam("{\"code\":\""+param+"\"}");;

        try {
            SendSmsResponse response = client.getAcsResponse(request);
            //这句话表示阿里云告诉你：短信是否发送成功，如果失败了可以看到具体原因
            System.out.println(new Gson().toJson(response));
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }
    }
}
